package interval;

import java.util.Arrays;

/**
 * @author pengfei.hpf
 * @date 2020/3/8
 * @verdion 1.0.0
 * 354. Russian Doll Envelopes
 * You have a number of envelopes with widths and heights given as a pair of integers (w, h). One envelope can fit into another if and only if both the width and height of one envelope is greater than the width and height of the other envelope.
 *
 * What is the maximum number of envelopes can you Russian doll? (put one inside other)
 *
 * Note:
 * Rotation is not allowed.
 *
 * Example:
 *
 * Input: [[5,4],[6,4],[6,7],[2,3]]
 * Output: 3
 * Explanation: The maximum number of envelopes you can Russian doll is 3 ([2,3] => [5,4] => [6,7]).
 * 通过次数6,934提交次数20,370
 */
public class MaxEnvelopes {
    public int maxEnvelopes(int[][] envelopes){
        if(envelopes == null || envelopes.length == 0 || envelopes[0].length == 0){
            return 0;
        }
        //TODO: 如果高度相同, 使用逆序,保证同一高度在选择的时候只选一个
        Arrays.sort(envelopes, (o1,o2) -> (o1[0] == o2[0]? o2[1] - o1[1]: o1[0] - o2[0]));
        int[] heights = new int[envelopes.length];
        for(int i = 0; i < envelopes.length; i++){
            heights[i] = envelopes[i][1];
        }
        return LTS(heights);
    }

    private int LTS(int[] heights){
        int[] nums = new int[heights.length];
        int res = 0;
        for(int i = 0; i < heights.length; i ++){
            int l = 0;
            int r = res;
            while(l < r){
                int mid = l + (r - l )/2;
                if(nums[mid] >= heights[i]){
                    r = mid;
                } else {
                    l = mid + 1;
                }
            }
            nums[l] = heights[i];
            if(l == res){
                res ++;
            }
        }
        return res;
    }

    public static void main(String[] args){

        System.out.println((new MaxEnvelopes()).maxEnvelopes(new int[][]{{5,4},{6,4},{6,7},{2,3}}));
    }
}
